// pages/3861.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
      status:'等待获取token',
      temp_s:'等待获取数据',
      humi_s:'等待获取数据',
      smoke_s:'等待获取数据',
      co_s:'等待获取数据',
      shouldGetData: false,
      progress: 0,
      pro_status: 2,
      progressLabel: 2,
    },

    updateProgressBar(pro_status) {
      const statusProgressMap = {
        1: 0,
        2: 30,
        3: 65,
        4: 100
      };
      const statusLabelMap = {
        1: '小车空闲',
        2: '小车准备中 目标桌号【{{value}}】',
        3: '小车送餐中 目标桌号【{{value}}】',
        4: '小车送餐完成 目标桌号【{{value}}】'
      };
      const progress = statusProgressMap[pro_status] || 0;
      const progressLabel = statusLabelMap[pro_status].replace('{{value}}',this.data.table_id);
      this.setData({
        progress: progress,
        pro_status: pro_status,
        progressLabel: progressLabel,
      });
    },

    toggleDataFetching: function() {
      this.setData({
        shouldGetData: !this.data.shouldGetData
      });
  
      // 根据状态变量来启动或停止定时器
      if (this.data.shouldGetData) {
        this.startFetchingData();
      } else {
        this.clearIntervalIfSet();
      }
    },
  
    startFetchingData: function() {
      // 如果已经设置了定时器，先清除
      this.clearIntervalIfSet();
      this.gettoken();
      // 设置定时器，每隔一定时间获取一次数据
      this.getDataInterval = setInterval(() => {
        if (this.data.shouldGetData) {
          this.getshadow();
        } else {
          this.clearIntervalIfSet();
        }
      }, 1000);
    },
  
    clearIntervalIfSet: function() {
      if (this.getDataInterval) {
        clearInterval(this.getDataInterval);
        this.getDataInterval = null;
        this.setData({status:'获取停止'});
      }
    },

    gettoken:function(){
      console.log("开始获取。。。");//打印完整消息
      var that=this;
      wx.request({
          url: 'https://iam.ap-southeast-1.myhuaweicloud.com/v3/auth/tokens',
          data:'{"auth": {"identity": {"methods": ["password"],"password": {"user": {"name": "SocialPanda","password": "3861hi","domain": {"name": "social_panda"}}}},"scope": {"project": {"name": "ap-southeast-1"}}}}',
          method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          header: {'content-type': 'application/json' }, // 请求的 header 
          success: function(res){// success
              that.setData({status:'获取token成功'});
              console.log("获取token成功");//打印完整消息
              console.log(res);//打印完整消息
              var token='';
              token=JSON.stringify(res.header['X-Subject-Token']);//解析消息头的token
              token=token.replaceAll("\"", "");
              console.log("获取token=\n"+token);//打印token
              wx.setStorageSync('token',token);//把token写到缓存中,以便可以随时随地调用
          },
          fail:function(){
              that.setData({status:'获取token失败'});
              console.log("获取token失败");//打印完整消息
          },
          complete: function() {
              console.log("获取token完成");//打印完整消息
          } 
      });
  },

  
  /**
  * 获取设备影子
  */
   getshadow:function(){
    console.log("开始获取影子");//打印完整消息
    var that=this;
    var token=wx.getStorageSync('token');//读缓存中保存的token
    wx.request({
        url: 'https://85cb03f441.st1.iotda-app.ap-southeast-1.myhuaweicloud.com/v5/iot/2661dad23e594e2794db300570251863/devices/6673807f0384a4349bb140e2_3861_HK/shadow',
        data:'',
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {'content-type': 'application/json','X-Auth-Token':token }, //请求的header 
        success: function(res){// success
            console.log(res);//打印完整消息
            var temp=JSON.stringify(res.data.shadow[0].reported.properties.temp);
            var humi=JSON.stringify(res.data.shadow[0].reported.properties.humi);
            var smoke_ppm=JSON.stringify(res.data.shadow[0].reported.properties.smoke_ppm);
            var co_ppm=JSON.stringify(res.data.shadow[0].reported.properties.co_ppm);
            var table_id=JSON.stringify(res.data.shadow[0].reported.properties.table_id);
            var car_status=JSON.stringify(res.data.shadow[0].reported.properties.car_status);
            console.log('温度='+temp+'℃');
            console.log('湿度='+humi+'%');
            console.log('烟雾='+smoke_ppm+'ppm');
            console.log('一氧化碳='+co_ppm+'ppm');
            console.log('小车状态'+car_status);
            console.log('桌号'+table_id);
            that.setData({status:'获取正常'});
            that.setData({temp_s:temp+'℃'});
            that.setData({humi_s:humi+'%'});
            that.setData({smoke_s:smoke_ppm+'ppm'});
            that.setData({co_s:co_ppm+'ppm'});
            that.setData({table_id:table_id});
            const pro_status = car_status;
            that.updateProgressBar(pro_status);
          },  
        fail:function(){
            console.log("获取影子失败");//打印完整消息
            console.log("请先获取token");//打印完整消息
        },
        complete: function() {
            console.log("获取影子完成");//打印完整消息
        } 
    });
  },

  button_getToken:function() {
    console.log("获取token按钮按下");
    this.setData({status:'获取token中'});
    this.gettoken();
  },

  button_getShadow:function() {
    console.log("获取影子按钮按下");
    this.setData({status:'获取影子中'});
    while(true) this.getshadow();
  },

  toggleStatus() {
    const statusList = [1, 2, 3, 4];
    const currentStatusIndex = statusList.indexOf(this.data.pro_status);
    const nextStatusIndex = (currentStatusIndex + 1) % statusList.length;
    const nextStatus = statusList[nextStatusIndex];
    this.updateProgressBar(nextStatus);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getDataInterval = null;
    this.updateProgressBar(options.pro_status || 1);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.clearIntervalIfSet();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})